import { BuildOutlined, PlusOutlined } from "@ant-design/icons";
import { BetaSchemaForm } from "@ant-design/pro-components";
import { PageContainer } from "@ant-design/pro-layout"
import ProTable, { ActionType } from "@ant-design/pro-table";
import type { CrudFilters } from "@refinedev/core";
import { SysIcon } from "@sker/model";
import { useModel, useModal, useForm, toWebUrl, useAxiosWebPost } from "@sker/sdk";
import { renderAdminPage, IconCategorySelector, SkerUploadOne, useServerData } from "@sker/ui"
import { App, Button, Card, Image, Modal, Popconfirm } from "antd";
import { useEffect, useRef, useState } from "react";


export const IconPage: React.FC<{}> = ({ }) => {
    const [serverData] = useServerData();
    const model = useModel(SysIcon)
    const uploadUrl = toWebUrl('imeepos/core/icon')
    const { props: modalProps, setOpen, setTitle } = useModal('添加图标', () => setRecord(null))
    const { fetch: buildIcon } = useAxiosWebPost('imeepos/core/icon/build', {})
    const [record, setRecord] = useState<any>()
    const [pres, setPres] = useState<string[]>()
    const actionRef = useRef<ActionType>()
    const app = App.useApp();
    const { props: formProps, form } = useForm([
        { title: '标题', dataIndex: 'svg_title' },
        { dataIndex: 'svg_name', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
        { dataIndex: 'pre', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
        { dataIndex: 'id', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
        { dataIndex: 'svg_path', fieldProps: { hidden: true }, formItemProps: { hidden: true } },
        {
            title: '图标',
            renderFormItem(schema, config, form, action) {
                const id = form.getFieldValue('id')
                const svg_path = form.getFieldValue('svg_path')
                const svg_name = form.getFieldValue('svg_name')
                const fileList: any[] = [];
                if (id) {
                    fileList.push({
                        uid: id,
                        url: svg_path,
                        name: svg_name,
                    })
                }
                return <SkerUploadOne value={fileList} action={uploadUrl} onUpload={(values) => {
                    form.setFieldsValue(values)
                }} />
            },
        },
    ], async (values) => {
        if (record) {
            values.id = record.id;
        }
        if (pres && pres.length > 0) values.pre = pres[0]
        if (!values.pre) {
            app.message.error(`请选择图标分组`)
            return;
        }
        await model.save(values, ['id'])
        setOpen(false)
        actionRef.current?.reload();
        setRecord(null)
    })
    useEffect(() => {
        if (!record) {
            form.resetFields()
            return;
        }
        form.setFieldsValue(record)
    }, [record])
    const toStr = (it: string) => it[0].toUpperCase() + it.slice(1)
    const toStrs = (it: string) => it.split('-').map(toStr).join('')
    return <PageContainer title={serverData?.title || '图标管理'} content={<div>
        推荐<a href={'https://www.iconfont.cn/'} target={'_blank'}>https://www.iconfont.cn/</a>下载svg上传，有改动时，点击构建按钮生效！可自动适应主题配色！
    </div>} extra={
        <>
            <Button type={'primary'} icon={<BuildOutlined />} onClick={async e => {
                await buildIcon({})
            }}>构建</Button>
        </>
    }>
        <div className="flex">
            <div className="w-400px">
                <IconCategorySelector onSelect={(keys: string[]) => {
                    if (keys.length > 0) {
                        form.setFieldValue('pre', keys[0])
                    }
                    setPres(keys)
                }} />
            </div>
            <div className="flex-1 ml-24px">
                <Modal {...modalProps}>
                    <BetaSchemaForm {...formProps} />
                </Modal>
                <Card title={'图标列表'} extra={
                    <>
                        <Button icon={<PlusOutlined />} type={'primary'} size="small" onClick={() => {
                            setRecord(null)
                            setOpen(true)
                        }}></Button>
                    </>
                }>
                    <ProTable
                        search={false}
                        toolBarRender={false}
                        actionRef={actionRef}
                        rowKey={record => `${toStrs(record.pre)}${toStrs(record.svg_name)}`}
                        columns={[
                            { title: '序号', dataIndex: 'icon_id' },
                            { title: '标题', dataIndex: 'svg_title' },
                            { title: '名称', dataIndex: 'svg_name' },
                            {
                                title: '图标', dataIndex: 'svg_path', render(dom, entity, index, action, schema) {
                                    return <Image width={'32px'} src={entity.svg_path} />
                                },
                            },
                            { title: '前缀', dataIndex: 'pre' },
                            {
                                title: '操作',
                                align: 'right',
                                render(dom, entity, index, action, schema) {
                                    return <>
                                        <Button size={'small'} type={'link'} onClick={e => {
                                            setTitle('编辑图标')
                                            setOpen(true)
                                            setRecord(entity)
                                        }}>编辑</Button>
                                        <Popconfirm onConfirm={async e => {
                                            await model.delete(entity.id)
                                            await actionRef.current?.reload();
                                        }} title={'此操作不可逆!您确定要执行此操作吗？'} description={'删除后无法恢复，请慎重操作！！'}>
                                            <Button size={'small'} type={'link'} danger >删除</Button>
                                        </Popconfirm>
                                    </>
                                },
                            }
                        ]}
                        params={{
                            pres
                        }}
                        request={async (params) => {
                            const filters: CrudFilters = [];
                            if (params.pres && params.pres.length > 0) {
                                filters.push({ field: 'pre', operator: 'in', value: params.pres })
                            }
                            return model.find(['id', 'icon_id', 'svg_name', 'svg_title', 'svg_path', 'pre'], [
                                ...filters
                            ], [{ field: 'icon_id', order: 'desc' }], {
                                current: params.current,
                                pageSize: params.pageSize
                            })
                        }}
                    />
                </Card>
            </div>
        </div>
    </PageContainer>
}

renderAdminPage(IconPage, 'imeepos/core/web/icon')